package com.cqc.other.juc.synchronize;

public class TicketDemo {

    static Object lock = new Object();
    int ticketNum = 10;

    /**
     * Thread-0抢到票了，还剩9张
     * Thread-3抢到票了，还剩9张
     * Thread-2抢到票了，还剩9张
     * Thread-1抢到票了，还剩9张
     * Thread-5抢到票了，还剩6张
     * Thread-4抢到票了，还剩8张
     * Thread-6抢到票了，还剩5张
     * Thread-8抢到票了，还剩3张
     * Thread-7抢到票了，还剩3张
     * Thread-9抢到票了，还剩0张
     */
    public static void main(String[] args) {
        TicketDemo ticketDemo = new TicketDemo();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                ticketDemo.getTicket1();
//                ticketDemo.getTicket2();
//                ticketDemo.getTicket3();
            }).start();
        }
    }

    /**
     * synchronized 加到方法上和加到代码块上，效果相同
     */
    public void getTicket1() {
        if (ticketNum <= 0) {
            return;
        }
        System.out.println(Thread.currentThread().getName() + "抢到票了，还剩" + (ticketNum - 1) + "张");
        ticketNum--;
    }

    public synchronized void getTicket2() {
        if (ticketNum <= 0) {
            return;
        }
        System.out.println(Thread.currentThread().getName() + "抢到票了，还剩" + (ticketNum - 1) + "张");
        ticketNum--;
    }

    public void getTicket3() {
        synchronized (this) {
            if (ticketNum <= 0) {
                return;
            }
            System.out.println(Thread.currentThread().getName() + "抢到票了，还剩" + (ticketNum - 1) + "张");
            ticketNum--;
        }
    }


}
